<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Kit\RedisKey;
use App\Kit\Token;
use App\Models\AdminModel;
use App\Models\AdminRoleModel;
use App\Models\StaffModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class Index extends Controller
{

    public function login(Request $request){
        $account = $request->input('account');
        $pwd = $request->input('password');

        $admin = AdminModel::where('account', $account)->first();
        if(!$admin) {
            return $this->error("用户名或密码错误");
        }

        if(!$admin->status) {
            return $this->error("账号已禁用");
        }

        if(!password_verify($pwd, $admin->password)){
            return $this->error("用户名或密码错误");
        }

        $authInfo = $admin->toArray();
        unset($authInfo['password']);
        unset($authInfo['token']);

        $effective_time = 86400;
        $token = Token::get_admin_token($admin->id);
        if(!$token) {
            $token = Token::createToken($authInfo, $admin->id, 'admin', $effective_time);
            Token::set_admin_token($token, $admin->id, $effective_time);
        }

        $info_key = RedisKey::admin_info($admin->id);
        $last_login_time = date('Y-m-d H:i:s');

        $authInfo['last_login_time'] = $last_login_time;
        Redis::set($info_key, json_encode($authInfo));

        $admin->last_login_time = $last_login_time;
        $admin->save();

        return $this->success(["token" => base64_encode($token)]);
    }


    public function pda_login(Request $request){
        $account = $request->input('account');
        $pwd = $request->input('password');

        $admin = AdminModel::where('account', $account)->whereHas('staff', function ($query) {
            $query->where('is_warehouse_staff', 1);
        })->first();

        if(!$admin) {
            return $this->error("用户名或密码错误");
        }

        if(!password_verify($pwd, $admin->password)){
            return $this->error("用户名或密码错误");
        }

        $authInfo = $admin->toArray();
        unset($authInfo['password']);
        unset($authInfo['token']);

        $effective_time = 86400;
        $token = Token::get_admin_token($admin->id);
        if(!$token) {
            $token = Token::createToken($authInfo, $admin->id, 'admin', $effective_time);
            Token::set_admin_token($token, $admin->id, $effective_time);
        }

        $info_key = RedisKey::admin_info($admin->id);
        $last_login_time = date('Y-m-d H:i:s');

        $authInfo['last_login_time'] = $last_login_time;
        Redis::set($info_key, json_encode($authInfo));

        $admin->last_login_time = $last_login_time;
        $admin->save();

        $user_info = [
            'id' => $admin->id,
            'staff_name' => $admin->staff->name ?? '',
            'dept_name' => $admin->staff->dept ? $admin->staff->dept->name : '',
            'warehouse_address' => $admin->staff->warehouse ? $admin->staff->warehouse->address : ''
        ];

        return $this->success(["token" => base64_encode($token), 'user_info' => $user_info]);
    }

    //账号信息
    public function info(Request $request){
        $auth = $request->get('auth');
        $data = [
            'id' => $auth->id,
        ];
        return $this->success($data);
    }

    //上传
    public function upload(Request $request)
    {
        // 验证请求中的文件
        $request->validate([
            'file' => 'required|file',
        ]);

        // 获取上传的文件
        $file = $request->file('file');

        // 获取原始文件名
        $originalFileName = $file->getClientOriginalName();
        $fileNameWithoutExtension = pathinfo($originalFileName, PATHINFO_FILENAME);

        // 读取文件内容并计算 MD5 哈希值
        $fileContent = file_get_contents($file->getPathname());
//        $md5FileName = md5($fileContent) . '.' . $file->getClientOriginalExtension();


        // 定义保存路径
        $upload_path = 'uploads/files/'. date('Ymd');
        $destinationPath = public_path($upload_path);
        
        // 确保目录存在
        if (!file_exists($destinationPath)) {
            mkdir($destinationPath, 0755, true);
        }

        // 返回保存的文件路径
        $filePath = $upload_path.'/'.$originalFileName;

        //如果文件存在
        if(file_exists($destinationPath.'/'.$originalFileName)) {
            $originalFileName = $fileNameWithoutExtension . '_' . date('YmdHis') . '.' . $file->getClientOriginalExtension();
            $filePath = $upload_path.'/'.$originalFileName;
        }

        // 移动文件到目标路径
        $file->move($destinationPath, $originalFileName);

        return $this->success(['path' => $filePath]);
    }

    public function test(Request $request) {
        $admin = AdminModel::get();

        foreach ($admin as $item){
            if(!$item->auth){
                $staff = StaffModel::find($item->staff_id);
                $role = AdminRoleModel::find($staff->role_id);
                $item->auth = $role->auth;
                $item->save();
            }
        }

        return $this->success();
    }

}
